import ssl
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
from os import curdir, sep
import cgi
import serialcom
import os
import base64

#true if closed
mGarageDoor = 1 
mSerial = serialcom.SerialCom()
i = 0

#This class will handles any incoming request from
#the browser 
class myHandler(BaseHTTPRequestHandler):
   
   #Handler for the GET requests
   def do_HEAD(self):
      self.send_response(200)
      self.send_header("Content-type", "text/html")
      self.end_headers()
   def do_AUTHHEAD(self):
      print "send header"
      self.send_response(401)
      self.send_header('WWW-Authenticate', 'Basic realm="login"')
      self.send_header('Content-type', 'text/html')
      self.end_headers()
   def do_GET(self):
      auth = self.headers.getheader('Authorization')
      print auth
      if auth == None:
         self.do_AUTHHEAD()
         self.wfile.write('no auth header received')
         pass
      elif auth == 'Basic bG9naW46cGFzc3dvcmQ=':         
         if self.path.endswith(".css"):
            f = open(curdir+sep+self.path)
            self.send_response(200)
            self.send_header('Content-type', 'text/css')
            self.end_headers()
            self.wfile.write(f.read())
            f.close()
         elif self.path.endswith("/"):
            self.WriteMainPage()
            pass
      else:
         self.do_AUTHHEAD()
         self.wfile.write(auth)
         self.wfile.write('not authenticated')
         pass
      return
   #Handler for the POST requests
   def do_POST(self):
      if self.path=="/trigger":
         form = cgi.FieldStorage(
            fp=self.rfile, 
            headers=self.headers,
            environ={'REQUEST_METHOD':'POST',
                       'CONTENT_TYPE':self.headers['Content-Type'],
         })
         mSerial.SendTriggerCmd()
         #would handle the sending of serial message to mcu
         self.WriteMainPage()
      return
   
   
   def WriteMainPage(self):
      global mGarageDoor
      self.send_response(200)
      self.send_header("Content-type", "text/html")
      self.end_headers()
      self.wfile.write("<html><head>")
      self.wfile.write("<title>Garage Door Opener</title>")
      self.wfile.write("<META http-equiv=\"refresh\" content=\"30;URL=https://108.12.26.80:4443\">")
      self.wfile.write("<link rel=\"stylesheet\" type=\"text/css\" href=\"mystyle.css\">")
      self.wfile.write("</head>")
      
      self.wfile.write("<div id=\"navigation\">")
      self.wfile.write("<div class=\"navigation\">") 
      self.wfile.write("<a href=\"#\">Home</a>")
      self.wfile.write("</div>")
      
      
      mGarageDoor = mSerial.SendRequestCmd()
      
      if mGarageDoor==-1: #Resend request
         mGarageDoor = mSerial.SendRequestCmd()
      
      if mGarageDoor==1:
         status = "<p>Garage door is closed </p>"
      elif mGarageDoor==0:
         status = "<p>Garage door is open </p>"
      else:
         status = "<p class=\"p_text\">Garage door is unknown </p>"
      self.wfile.write("<h2>Garage Door</h2>")
      self.wfile.write("<body id=\"background-wrap\">")
      self.wfile.write(status)
      self.wfile.write("<form method=\"POST\" action=\"/trigger\">")
      self.wfile.write("<div class=\"buttonHolder\">")
      self.wfile.write("<input class=\"button_example\" type=\"submit\" value=\"Garage Door\"/>")
      self.wfile.write("</div></form>")
      self.wfile.write("</div>")
      self.wfile.write("</body></html>")
      return
   
if __name__=='__main__':
   try:
      httpd = HTTPServer(('', 4443), myHandler)
      abcd = "%s:%s"%("login", "password")
      try:
         auth = base64.b64encode(abcd)
      except TypeError:
         auth = base64.b64encode(abcd.encode()).decode()
      httpd.socket = ssl.wrap_socket (httpd.socket, certfile='server.pem', server_side=True)
      #httpd.serve_forever()
      while 1:
         httpd.handle_request()
         print('Hello')
   except KeyboardInterrupt:
      print '^C received, shutting down the web server'
      httpd.socket.close()
